﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using LPV_POS.mh_pos;
using LPV_POS.manhinh;
using System.IO;
using LPV_POS.Module;
using LPV_POS.mh_pos.mh_danhmuc;
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Text;
using LPV_POS.In;
using System.Threading;
using Create_License;

namespace LPV_POS
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]

        static void Main()
        {
            //MessageBox.Show("0");
            #region "Kiem tra hang dung"
            //////-----------------------------------Begin kiem tra han dung -------------------------------------
            //if (File.Exists(Application.StartupPath + @"\deadline.lsys"))
            //{
            //    #region "Kiem tra thoi gian su dung"
            //    string _deadline = "";
            //    StreamReader _file_read = new StreamReader(Application.StartupPath + @"\deadline.lsys");
            //    if (_file_read.Read() > 0)
            //    {
            //        _deadline = _file_read.ReadToEnd().Trim();  //new cpublic().GiaiMa("", _file_read.ReadToEnd().Trim());
            //        string _sql = "UPDATE DM_FUNCTION SET CACDICHVU_2 = '" + _deadline + "'";
            //        int _ketqua = new thuvien().SP_Update("SP_EXECUTESQL", new string[] { "sSQL" }, new object[] { _sql });
            //        _file_read.Close();
            //        File.Delete(Application.StartupPath + @"\deadline.lsys");
            //        // luu vao database roi kiem tra
            //        DataTable tb_1 = new thuvien().SP_SelectDataTable("[SP_GETDATE]", new string[] { "@flag", "@choose" }, new object[] { 1, 2 });
            //        string _resul_deadline = tb_1.Rows[0]["CACDICHVU_2"] + "";
            //        _resul_deadline = new cpublic().GiaiMa("", _resul_deadline);
            //        if (_resul_deadline.Contains("#"))
            //            _resul_deadline = _resul_deadline.Split('#')[1] + "";
            //        string _cur_datetime = tb_1.Rows[0]["NGAYHIENHANH"] + "";
            //        decimal _kq1, _kq2;
            //        decimal.TryParse(_resul_deadline, out _kq1);
            //        decimal.TryParse(_cur_datetime, out _kq2);
            //        if (_kq2 > _kq1)
            //        {
            //            Mod_messagebox mes = new Mod_messagebox();
            //            mes.messagebox_pos("LPV-POS", "Phần mềm đã hết hạn dùng.", loaithongbao.canhbao.GetHashCode());
            //            //MessageBox.Show("Phần mềm đã hết hạn dùng", "Thông báo");
            //            return;
            //        }
            //    }
            //    #endregion
            //}
            //else
            //{
            //    #region "   neu khong ton tai file thi kiem tra phan mem con han dung khong"
            //    DataTable tb_1 = new thuvien().SP_SelectDataTable("[SP_GETDATE]", new string[] { "@flag", "@choose" }, new object[] { 1, 2 });
            //    string _resul_deadline = tb_1.Rows[0]["CACDICHVU_2"] + "";
            //    _resul_deadline = new cpublic().GiaiMa("", _resul_deadline);
            //    if (_resul_deadline.Contains("#"))
            //        _resul_deadline = _resul_deadline.Split('#')[1] + "";
            //    string _cur_datetime = tb_1.Rows[0]["NGAYHIENHANH"] + "";
            //    decimal _kq1, _kq2;
            //    decimal.TryParse(_resul_deadline, out _kq1);
            //    decimal.TryParse(_cur_datetime, out _kq2);
            //    if (_kq2 > _kq1)
            //    {
            //        Mod_messagebox mes = new Mod_messagebox();
            //        mes.messagebox_pos("LPV-POS", "Phần mềm đã hết hạn dùng.", loaithongbao.canhbao.GetHashCode());
            //        //MessageBox.Show("Phần mềm đã hết hạn dùng", "Thông báo");
            //        return;
            //    }
            //    #endregion
            //}
            ////    //----------------------------------- End kiem tra han dung -------------------------------------
            #endregion
            //MessageBox.Show("00");

            if (1 == 1)
            {
                if (1 == 2)
                {
                    #region "   Kiem tra License - Cu~"
                    //MessageBox.Show("");
                    if (!File.Exists(Application.StartupPath + @"\System.txt"))
                    {
                        Mod_messagebox mes = new Mod_messagebox();
                        mes.messagebox_pos("LPV-POS", "Phần mềm chưa đăng ký bản quyền.", loaithongbao.canhbao.GetHashCode());
                        //MessageBox.Show("Phần mềm chưa đăng ký bản quyền.", "LPV-POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        //MessageBox.Show("1");///////////////////////////////////////////
                        StreamReader str = new StreamReader(Application.StartupPath + @"\System.txt", System.Text.Encoding.Unicode);
                        //MessageBox.Show("2");///////////////////////////////////////////
                        Create_License.XuLy oXuLy = new Create_License.XuLy();
                        str.ReadLine();
                        str.ReadLine();
                        str.ReadLine();
                        //MessageBox.Show("3");///////////////////////////////////////////
                        string CDKey = oXuLy.gfDeCodeText(str.ReadLine());
                        //MessageBox.Show("4");///////////////////////////////////////////
                        str.ReadLine();
                        //MessageBox.Show("5");///////////////////////////////////////////
                        string ID = oXuLy.GetSerialNumber1();
                        //MessageBox.Show("6");///////////////////////////////////////////
                        CDKey = oXuLy.GiaiMa(CDKey);
                        //MessageBox.Show("7");///////////////////////////////////////////
                        if (CDKey != ID)
                        {
                            //MessageBox.Show("8");///////////////////////////////////////////
                            new Mod_messagebox().messagebox_pos("LPV-POS", "Phần mềm chưa đăng ký bản quyền.", loaithongbao.canhbao.GetHashCode());
                            return;
                        }
                        //MessageBox.Show("9");///////////////////////////////////////////
                    }
                    #endregion
                }
                else if (3 == 3)
                {
                    
                    #region "   kiem tra dongle"
                    
                    if (new Run_Application.AXDongle().InitDongle())
                    {
                        
                        byte[] arr = new Run_Application.AXDongle().GetData();
                        
                        if (arr != null)
                        {
                            
                            if (arr[4] != 1)//Cho phép chay LPV-POS
                            {
                                MessageBox.Show("Không tìm thấy Dongle.", "LPV-POS", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            goto ok;
                        }
                    }
                    
                    {
                        #region "   Kiem tra License - Moi"
                    //ID key lấy từ registry
                        Run:
                        Create_License.XuLy oXuLy = new Create_License.XuLy();
                        string ID = Create_License.XuLy.Registry_Get(Create_License.XuLy.KeySQL, Create_License.XuLy.pathSQL);
                        ID = oXuLy.GiaiMa(ID) + "";
                        if (ID + "" == "")
                        {
                            //Nếu ID là "" hiển thị form Đăng ký
                            Create_License.frmDangKy frm = new Create_License.frmDangKy();
                            frm.ShowDialog();
                            if (frm.FlagClose == true)
                                return;
                            //Kiểm tra lại License
                            goto Run;
                        }
                        
                        //Get serial number of PC
                        //string IDKey = XuLy.GetSerialNumber_str();
                        
                        
                        //if (IDKey == "")
                        //{
                        //    return;
                        //}
                        
                        ////Kiểm tra License
                        //string[] arr = ID.Split('-');
                        //string Lic = "";
                        //for (int i = 0; i < arr.Length; i++)
                        //{
                        //    Lic += arr[i];
                        //}
                        
                        //string chuoicat = Lic.Substring(0, IDKey.Length);
                        
                        //string ChuoiDoi = Create_License.XuLy.ChuyenDoi(chuoicat);
                        
                        ////Kiem tra ID
                        //if (IDKey != ChuoiDoi)
                        //{
                            
                        //    Create_License.frmDangKy frm = new Create_License.frmDangKy();
                        //    frm.ShowDialog();
                        //    if (frm.FlagClose == true)
                        //        return;
                        //    goto Run;
                        //}
                        
                        if (!File.Exists(Application.StartupPath + @"\System.dll"))
                        {
                            MessageBox_LPV.Show("Vui lòng chép File System.dll vào thư mục phần mềm.\n File trong Thư mục : D:\\License");
                            return;
                        }
                        else
                        {
                            StreamReader str = new StreamReader(Application.StartupPath + @"\System.dll", System.Text.Encoding.Unicode);

                            str.ReadLine();
                            str.ReadLine();
                            str.ReadLine();
                            string CDKey = new XuLy().GiaiMa(str.ReadLine());
                            str.ReadLine();
                            //Kiểm tra lần 2
                            if (ID != CDKey)
                            {
                                Create_License.frmDangKy frm = new Create_License.frmDangKy();
                                frm.ShowDialog();
                                if (frm.FlagClose == true)
                                    return;
                                goto Run;
                            }
                        }


                        #endregion
                    }
                   
                    #endregion
                    
                }
                else
                {
                    
                }
            }
            ok:
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
            }
            catch (Exception)
            {
                Application.Exit();
            }

            #region "   Share Máy in"
            cpublic ocpublic = new cpublic();
            Boolean bShare_May_In = ocpublic.Registry_Get("SHARE_ELLIX") + "" == "True";
            if (bShare_May_In)
            {//Nếu có share máy in
                Boolean bMay_Nhan_DuLieu_In = true;
                if (bMay_Nhan_DuLieu_In)
                {
                    #region "   Nếu là máy nhận dữ liệu"
                    String strHostName = Dns.GetHostName();
                    IPHostEntry oIPHostEntry = Dns.GetHostByName(strHostName);
                    int iPort = 5555 + DateTime.Now.Second;
                    IPEndPoint oIPEndPoint = new IPEndPoint(oIPHostEntry.AddressList[0], iPort);
                    Thread oThread = new Thread(ReceiveData);
                    oThread.IsBackground = true;
                    try
                    {
                        oThread.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message,"Main");
                    }
                    #endregion
                }
                else
                { //Máy gửi dữ liệu

                }
            }
            #endregion
            //Application.Run(new LPV_POS.hinh.frmScreen());
            Application.Run(new mh_main());
            //Application.Run(new LPV_POS.mh_pos.mh_doanhthu.Nhap());
           
        }

        #region "   ReceiveData"
        static void ReceiveData()
        {
            UdpClient client = new UdpClient(8888);
            while (true)
            {
                try
                {
                    IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 8888);
                    byte[] data = client.Receive(ref anyIP);
                    string text = Encoding.UTF8.GetString(data);

                    if (text.IndexOf("bep") == 0)
                    {
                        #region "   in bep"
                        //0. omayin
                        //1. DM_MAYIN_BEP_MA
                        //2.iPrintOut -- so ban in
                        //3.sdata
                        text = text + "";
                        //string sMa_may_In_Bep = "";

                        In_TamTinh_Bep(text);
                        #endregion
                    }
                    else if (text.IndexOf("hoadon") == 0)
                    {
                        #region "   in HD tam tinh"
                        string[] adata = text.Replace("\r\n", "#").Split('#');
                        //0. omayin
                        //1. DM_MAYIN_BEP_MA
                        //2.iPrintOut -- so ban in
                        //3.ma_phieu
                        if (adata.Length > 3)
                        {
                            string sBH_PHIEU_TMP = adata[3];
                            if (sBH_PHIEU_TMP != "")
                            {
                                int iPrintOut = 0;
                                int.TryParse(adata[2] + "", out iPrintOut);
                                while (iPrintOut > 0)
                                {
                                    print_BAN_HANG oprint_BAN_HANG = new print_BAN_HANG();
                                    oprint_BAN_HANG.Print_PHIEU_BANHANG(sBH_PHIEU_TMP, false);
                                    iPrintOut--;
                                }
                            }
                        }
                        #endregion
                    }
                    else if (text.IndexOf("thanhtoan") == 0)
                    {
                        #region "   in HD thanh toan"
                        string[] adata = text.Replace("\r\n", "#").Split('#');
                        //0. omayin
                        //1. DM_MAYIN_BEP_MA
                        //2.iPrintOut -- so ban in
                        //3.ma_phieu
                        if (adata.Length > 3)
                        {
                            string sBH_PHIEU_TMP = adata[3];
                            if (sBH_PHIEU_TMP != "")
                            {
                                int iPrintOut = 0;
                                int.TryParse(adata[2] + "", out iPrintOut);
                                while (iPrintOut > 0)
                                {
                                    print_BIEN_NHAN Oprint_BIEN_NHAN = new print_BIEN_NHAN();
                                    Oprint_BIEN_NHAN.Print_PHIEU_BIENNHAN(sBH_PHIEU_TMP);
                                    iPrintOut--;
                                }
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message,"ReceiveData");
                }
            }
        }

        static void In_TamTinh_Bep(string text)
        {
            string[] aText = text.Split('#');
            if (aText.Length <= 7)
                return;
            PrintCOMs oPrintCOM = new PrintCOMs(PrintCOMs.Print_Type.Print_KitChen);
            SerialPort_LPV[] SerialPort_LPVs = oPrintCOM.Print_Start();
            if (SerialPort_LPVs != null)
            {
                #region "   tbDM_MAYIN_BEP_CAUHINH"
                Boolean bIN_Gia = false;
                Boolean bIN_TEN_HANGHOA = false;
                Boolean bIN_TEN_BAN = false;
                Boolean bIN_SO_HOADON = false;
                Boolean bIN_MOIMON_MOTPHIEU = false;

                DataTable tbDM_MAYIN_BEP_CAUHINH = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { "SELECT * FROM DM_MAYIN_BEP_CAUHINH" });
                if (tbDM_MAYIN_BEP_CAUHINH.Rows.Count > 0)
                {
                    bIN_Gia = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_GIA"] + "") == "True";
                    bIN_SO_HOADON = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_SO_HOADON"] + "") == "True";
                    bIN_TEN_BAN = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_TEN_BAN"] + "") == "True";
                    bIN_TEN_HANGHOA = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_TEN_HANGHOA"] + "") == "True";
                    bIN_MOIMON_MOTPHIEU = (tbDM_MAYIN_BEP_CAUHINH.Rows[0]["IN_MOIMON_MOTPHIEU"] + "") == "True";
                }

                #endregion

                #region "   khai bao bien"
                string sDS_May_In = aText[aText.Length - 1].Replace("DS_May_In_;", "");
                string[] aDS_May_In = sDS_May_In.Split(';');

                #region  "  Top - Bottom"
                string sTieuDe_MoRong = "";
                string lblKhuVuc_Ban = "";
                string sMaphieu = "";
                string lblcalamviec = "";
                string sTennv = "";
                string sTennv_PHUCVU = "";
                #endregion

                #region "   Content"
                string TenHangHoa = "";
                string SO_LUONG = "";
                string DON_GIA = "";
                string GHI_CHU = "";
                #endregion


                #endregion

                
                foreach (SerialPort_LPV oSerialPort_LPV in SerialPort_LPVs)
                {
                    if (oSerialPort_LPV != null)
                    {
                        if (aDS_May_In.Contains(oSerialPort_LPV.OBJID))
                        {
                            if (!oSerialPort_LPV.IsOpen)
                                oSerialPort_LPV.Open();
                            {
                                if (sTieuDe_MoRong == "")
                                {
                                    sTieuDe_MoRong = aText[1].Replace("Top_sTieuDe_MoRong_", "").Trim();
                                    lblKhuVuc_Ban = aText[2].Replace("Top_lblKhuVuc_Ban_", "").Trim();
                                    sMaphieu = aText[3].Replace("Top_sMaphieu_", "").Trim();
                                    lblcalamviec = aText[4].Replace("Top_lblcalamviec_", "").Trim();
                                    sTennv = aText[aText.Length - 2].Replace("Bottom_sTennv_", "").Trim();
                                    sTennv_PHUCVU = aText[aText.Length - 3].Replace("Bottom_sTennvPV_", "").Trim();
                                }
                                #region  "  Top"
                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, "[" + oSerialPort_LPV.OBJNAME + "]" + sTieuDe_MoRong, "", "", "");

                                if (bIN_TEN_BAN && bIN_SO_HOADON)
                                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, lblKhuVuc_Ban + "", "", "", "");
                                //else if (bIN_SO_HOADON)
                                //    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, sMaphieu, "", "", "");
                                else if (bIN_TEN_BAN)
                                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Double_Height, lblKhuVuc_Ban + "", "", "", "");

                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, lblcalamviec, "", sMaphieu, "");
                                oPrintCOM.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, '=', PrintCOMs.Fills.Fills_Full);
                                #endregion

                                for (int ir = 5; ir < aText.Length - 1; ir++)
                                {
                                    if (aText[ir].IndexOf("Content_") == 0)
                                    {
                                        #region "   Content"
                                        if (aText[ir].IndexOf("Content_" + oSerialPort_LPV.OBJID + "_") < 0)
                                            ir += 3;
                                        else
                                        {
                                            TenHangHoa = aText[ir++].Replace("Content_" + oSerialPort_LPV.OBJID + "_TenHangHoa_", "").Trim();
                                            SO_LUONG = aText[ir++].Replace("Content_" + oSerialPort_LPV.OBJID + "_SO_LUONG_", "").Trim();
                                            DON_GIA = aText[ir++].Replace("Content_" + oSerialPort_LPV.OBJID + "_Gia_", "").Trim();
                                            GHI_CHU = aText[ir].Replace("Content_" + oSerialPort_LPV.OBJID + "_Ghi_Chu_", "").Trim();
                                            if (!bIN_TEN_HANGHOA)
                                                TenHangHoa = "";

                                            PrintCOMs.Fonts oFonts_KitChen = PrintCOMs.Fonts.Font_Double_Height;
                                            int iChieuDai_1Dong_In = 42;



                                            if (bIN_Gia)
                                            {
                                                
                                                //oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, oFonts_KitChen, TenHangHoa, "", "", SO_LUONG);
                                                oSerialPort_LPV.WriteLine(f_splitString3Column(TenHangHoa, SO_LUONG, DON_GIA, 29, 13));
                                                //oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, oFonts_KitChen, DON_GIA, "", "", "");
                                            }
                                            else
                                            {
                                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, oFonts_KitChen, TenHangHoa, "", "", SO_LUONG);
                                            }
                                            if (GHI_CHU.Trim() != "")
                                            {
                                                string _Ghi_Chu_2 = "";
                                                #region "   _Ghi_Chu_2"
                                                if (GHI_CHU.Length >= iChieuDai_1Dong_In)
                                                {
                                                    int iSpace = 0;
                                                    int icount = 0;
                                                    while (icount < iChieuDai_1Dong_In)
                                                    {
                                                        if (GHI_CHU.IndexOf(' ', icount) == icount)
                                                            iSpace = icount;
                                                        icount++;
                                                    }
                                                    string sTmp = "";

                                                    sTmp = GHI_CHU.Substring(0, iSpace).Trim();
                                                    _Ghi_Chu_2 = GHI_CHU.Substring(iSpace).Trim();
                                                    GHI_CHU = sTmp;

                                                }

                                                #endregion

                                                //---------------------------------------

                                                if (SO_LUONG.IndexOf("-") < 0)
                                                {//THEM MON
                                                    oSerialPort_LPV.WriteLine(GHI_CHU.Trim());
                                                    if (_Ghi_Chu_2 != "")
                                                        oSerialPort_LPV.WriteLine(_Ghi_Chu_2.Trim());
                                                }
                                                else//SL < 0 ==> 
                                                {//TRA MON
                                                    oSerialPort_LPV.WriteLine(GHI_CHU.Trim().Replace("Ghi chu", "Ly do"));
                                                    if (_Ghi_Chu_2 != "")
                                                        oSerialPort_LPV.WriteLine(_Ghi_Chu_2.Trim());
                                                }
                                            }

                                            if (bIN_MOIMON_MOTPHIEU)
                                                oPrintCOM.Print_Bottom(oSerialPort_LPV);
                                        }
                                        #endregion
                                    }
                                }

                                #region "   Bottom"
                                oPrintCOM.Print_Line(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, '=', PrintCOMs.Fills.Fills_Full);
                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, sTennv, "", "", "");

                                if (sTennv_PHUCVU.Trim() != "Nhan vien phuc vu:")
                                    oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Left, PrintCOMs.Fonts.Font_Normal, sTennv_PHUCVU, "", "", "");
                                
                                string Ngay = "* NGAY: " + Variable.ngay_gio_hienhanh.ToString("dd-MM-yyyy HH:mm") + " *";

                                oPrintCOM.Print_Content(oSerialPort_LPV, PrintCOMs.aligns.Align_Center, PrintCOMs.Fonts.Font_Normal, Ngay, "", "", "");

                                oPrintCOM.Print_Bottom(oSerialPort_LPV);
                                #endregion

                                if (oSerialPort_LPV.IsOpen)
                                    oSerialPort_LPV.Close();
                            }
                        }
                        oPrintCOM.Print_Close();
                    }
                }
            }
        }
        #region "   f_splitString3Column"
        static string f_splitString3Column(string a, string b, string c, int i1, int i2)
        {//i1: 29; i2:13
            cpublic ocpublic = new cpublic();
            string str = "";
            a = ocpublic.RemoveSign4VietnameseString(a).Trim();
            str = a;
            str += ocpublic.Spacestring(i1 - a.Length - b.Length);
            str += b;
            str += ocpublic.Spacestring(i2 - c.Length);
            str += c;
            return str;
        }
        #endregion
        #endregion
    }
}
